<script setup lang="ts">
import addToSignUpMessage from "./components/addToSignUpMessage.vue";
import { frequencyType } from "@/config/dictionary";
import { zoonType } from "../components/config";
import { deepClone } from "@/utils";
import PrizePool from "./PrizePool.vue";
import RewardSelector from "./RewardSelector.vue";
import Limits from "@/components/limits/Index.vue";

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
});

const isEdit = ref(false);
const emits = defineEmits(["change", "update:modelValue"]),
  activityId = inject("activityId", { value: "" }),
  activityReadonly = inject("activityReadonly", false);
const formData: any = inject("pageConfig");
// taskList = inject("taskList", { value: [] });

const showForm = computed(() => {
  return Boolean(
    formData.value.find((item: any) => item.type == "ToSignUp").pageConfig
      .signUpInformation
  );
});
const form = ref<any>({
  lotteryConfig: 0,
  subType: "ToSignUp",
});
const toSignUpTime = ref([] as any);
const toSignUpRef = ref();
const actEntryConfig = ref({
  startTime: "" as number | string,
  endTime: "" as number | string,
  actRewards: [{ scene: "ENTRY", rewardNum: 1 }], // 报名成功奖励
  fieldConfig: [] as any, // 配置信息
});

const typeData = ref({
  input: "单行文本",
  textarea: "多行文本",
  radio: "单项选择",
  check: "多项选择",
  number: "数值输入",
  date: "日期",
  area: "省市区",
});
const indexItem = ref("" as any);
const dataItem = ref({ name: "" } as any);
const formRef = ref();
const poolRef = ref();
const defaultTime: [Date, Date] = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
];
const rules = {
  // partTotalNum: [{ required: true, message: "请输入参与总次数", trigger: "blur" }],
  // groupAccomNum: [{ required: true, message: "请填写完成任务数量", trigger: "blur" }],
  time: [
    { required: true, message: "请填写报名时间", trigger: ["change", "blur"] },
  ],
};

const showDialog = ref(false);

const delItem = (idx: number) => {
  actEntryConfig.value.fieldConfig.splice(idx, 1);
  emits("change");
  updateData();
};
const addItem = (idx: number) => {
  indexItem.value = idx + 1;
  showDialog.value = true;
};
// 上移
const upItem = (idx: number) => {
  swapItems(actEntryConfig.value.fieldConfig, idx, idx - 1);
  emits("change");
  updateData();
};
// 下移
const downItem = (idx: number) => {
  swapItems(actEntryConfig.value.fieldConfig, idx, idx + 1);
  emits("change");
  updateData();
};
// 位置调换
const swapItems = (arr: any, index1: any, index2: any) => {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
};
const toEdit = (item: any, idx: any) => {
  dataItem.value = deepClone(item);
  indexItem.value = idx;
  isEdit.value = true;
  showDialog.value = true;
};

const editData = (data: any) => {
  isEdit.value = false;
  actEntryConfig.value.fieldConfig.splice(indexItem.value, 1, data);
  updateData();
  emits("change");
};
const confirm = (data: any) => {
  actEntryConfig.value.fieldConfig.push(data);
  updateData();
  emits("change");
};
const cancel = () => {
  showDialog.value = false;
  dataItem.value = { name: "" };
  nextTick(() => {
    indexItem.value = "";
  });
};

const prizeAreas = ref([] as any);
const updateData = () => {
  emits("update:modelValue", {
    pageArea: form.value,
    prizeAreas: prizeAreas.value,
    actEntryConfig: actEntryConfig.value,
  });
  emits("change");
};
// 添加奖池商品
const addPoolPrize = (index: number) => {
  poolRef.value.addPrize(1, index);
};

// 添加奖池
const addPool = () => {
  poolRef.value.addPool();
};

const prizePoolType = computed(() => {
  return form.value.subType ? zoonType[form.value.subType].prizePool || [] : [];
});
watch(toSignUpTime, (val) => {
  /* ... */
  if (val) {
    actEntryConfig.value.startTime = new Date(toSignUpTime.value[0]).getTime();
    actEntryConfig.value.endTime = new Date(toSignUpTime.value[1]).getTime();
  } else {
    actEntryConfig.value.startTime = "";
    actEntryConfig.value.endTime = "";
  }
});

const stopWatch = watch(
  () => props.modelValue,
  (val) => {
    nextTick(() => {
      stopWatch();
      formatData(val);
    });
  },
  {
    immediate: true,
  }
);

const formatData = (val: any) => {
  console.log("[ val ]", val);
  form.value = Object.assign({}, form.value, {
    ...val.pageArea,
    lotteryLimit:
      val.pageArea.lotteryLimit && typeof val.pageArea.lotteryLimit === "string"
        ? JSON.parse(val.pageArea.lotteryLimit)
        : [{ type: 1, limitNum: 1 }],
    lotteryLimitType: val.pageArea.lotteryLimit ? 1 : 0,
    partLimit: null,
  });

  actEntryConfig.value =
    val.actEntryConfig ||
    Object.assign({}, actEntryConfig.value, {
      pageFlag: form.value.pageFlag,
      actId: activityId.value,
    });
  if (!actEntryConfig.value["actId"]) {
    actEntryConfig.value.actRewards[0]["id"] = "";
    actEntryConfig.value.actRewards[0]["actId"] = "";
  }
  console.log("[ actEntryConfig.value ]", actEntryConfig.value);

  prizeAreas.value = val.prizeAreas || [];

  toSignUpTime.value = [
    new Date(actEntryConfig.value.startTime),
    new Date(actEntryConfig.value.endTime),
  ];
  updateData();
};

// // 添加奖池
// const addPool = () => {
//   poolRef.value.addPool();
// };

// // 添加奖池奖品
// const addPoolPrize = (index: number) => {
//   poolRef.value.addPrize(1, index);
// };

const quotePrize = computed(() => {
  // let rewardList: Array<any> = [];
  // if (form.value.taskStyle == 0) {
  //   for (let i = 0; i < toSignUpConfig.value.taskList.length; i++) {
  //     let reward = toSignUpConfig.value.taskList[i].rewardList || [];
  //     rewardList = rewardList.concat(reward);
  //   }
  // } else rewardList = toSignUpConfig.value.reward || [];
  // let prize = rewardList.filter((item: any) => {
  //   if (item.rewardType === "PRIZE") {
  //     return true;
  //   }
  //   return false;
  // });
  // if (prize && prize.length > 0) {
  //   return prize.map((item: any) => {
  //     return {
  //       prizeId: item.prizeId,
  //       poolId: item.prizeArea,
  //       specId: item.prizeSpec,
  //     };
  //   });
  // }
  return [];
});

const showPrizePool = computed(() => {
  // 开启抽奖，展示抽奖配置
  if (form.value.lotteryConfig == 1) {
    return true;
  }
  return false;
});

// const updateData = () => {
//   emits("update:modelValue", {
//     pageArea: form.value,
//     prizeAreas: prizeAreas.value,
//     actTaskConfig: taskConfig.value,
//   });
//   emits("change");
// };
const submit = () => {
  return new Promise((resolve, reject) => {
    if (showForm.value && !actEntryConfig.value.fieldConfig.length) {
      reject("请添加报名信息");
    }
    toSignUpRef.value.validate(async (valid: any, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        let actEntryConfigData = {};

        // 每人中奖限制
        // if (detail.lotteryLimitType == 0) {
        //   detail.lotteryLimit = "";
        // } else if (detail.lotteryLimit)
        detail.lotteryLimit = JSON.stringify(detail.lotteryLimit);

        try {
          // 任务区域
          actEntryConfigData = await checkTask();
          // 检查奖池
          await poolRef.value.check(
            detail.lotteryLimitType === 1 || detail.lotteryTotalLimit === 1,
            true
          );
        } catch (e) {
          reject(e);
        }

        // let actEntryConfigData: any = deepClone(actEntryConfig.value)
        // actEntryConfigData.fieldConfig = JSON.stringify(actEntryConfigData.fieldConfig)
        resolve({
          pageArea: detail,
          prizeAreas: prizeAreas.value,
          actEntryConfig: actEntryConfigData,
        });
      } else {
        toSignUpRef.value.scrollToField(Object.keys(invalidFields)[0]);
        reject("请检查基础信息配置");
      }
    });
  });
};

const checkTask = (): any => {
  return new Promise((resolve, reject) => {
    toSignUpRef.value.validate(async (valid: any) => {
      if (valid) {
        let detail: any = deepClone(actEntryConfig.value);

        // if (detail.taskStyle == 1) {
        //   if (detail.rewardList.length == 0) {
        //     reject(`请配置任务奖励`);
        //   }
        detail.actRewards.forEach((reward: any) => {
          if (reward.lotteryAreaUid) reward.lotteryArea = "";
          if (reward.prizeAreaUid) reward.prizeArea = "";
          if (reward.prizeUid) reward.prizeId = "";
          if (reward.prizeSpecUid) reward.prizeSpec = "";
          if (reward.ticketAct === "local") reward.ticketAct = "";
        });
        // detail.taskList.forEach((item: any) => {
        //   if (detail.taskStyle == 0) {
        //     if (item.rewardList.length == 0) {
        //       currentTaskIndex.value = item.id || item.uid;
        //       reject(`请配置【${item.name}】任务奖励`);
        //     }
        //     item.rewardList.forEach((reward: any) => {
        //       if (reward.lotteryAreaUid) reward.lotteryArea = "";
        //       if (reward.prizeAreaUid) reward.prizeArea = "";
        //       if (reward.prizeUid) reward.prizeId = "";
        //       if (reward.prizeSpecUid) reward.prizeSpec = "";
        //       if (reward.ticketAct === "local") reward.ticketAct = "";
        //     });
        //   }

        //   if (item.taskId instanceof Array) {
        //     item.taskId = item.taskId[0];
        //   }
        // });

        detail.fieldConfig = JSON.stringify(detail.fieldConfig);
        resolve(detail);
      } else reject(`请检查${form.value.name}配置`);
    });
  });
};

defineExpose({ submit, refresh: formatData });
</script>
<template>
  <el-form
    ref="toSignUpRef"
    :model="actEntryConfig"
    :rules="rules"
    :disabled="activityReadonly"
    label-width="auto"
  >
    <h3 class="collpase-title">报名配置</h3>
    <!-- <div>不添加报名信息则默认收集用户的登录唯一标识信息</div> -->
    <el-form-item class="to-sign-up-time" label="报名时间：" prop="startTime">
      <el-date-picker
        v-model="toSignUpTime"
        type="datetimerange"
        :default-time="defaultTime"
        range-separator="~"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
      />
    </el-form-item>
    <el-form-item v-if="showForm" label="报名信息：">
      <el-button style="margin-bottom: 10px" type="primary" @click="addItem(0)">
        添加字段
      </el-button>
      <div class="message">
        <template v-for="(item, idx) in actEntryConfig.fieldConfig" :key="idx">
          <div class="item">
            <el-form-item :label="`${typeData[item.type]}`" label-width="70px">
              <div class="message-value" @click="toEdit(item, idx)">
                {{ item.name }}
              </div>
              <div class="_item_operation">
                <el-button type="primary" link @click="addItem(idx)"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  link
                  @click="upItem(idx)"
                  :disabled="idx == 0"
                  >上移</el-button
                >
                <el-button
                  type="primary"
                  link
                  @click="downItem(idx)"
                  :disabled="idx == actEntryConfig.fieldConfig.length - 1"
                  >下移</el-button
                >
                <el-button type="primary" link @click="delItem(idx)"
                  >删除</el-button
                >
              </div>
              <!-- <el-icon :size="20" @click="delItem(idx)"><Close /></el-icon> -->
            </el-form-item>
          </div>
        </template>
      </div>
    </el-form-item>
    <el-form-item label="报名成功奖励：">
      <RewardSelector
        v-model="actEntryConfig.actRewards[0]"
        :subType="form.subType"
        :lottery="true"
        :prizeAreas="prizeAreas"
        prefix="actRewards.0."
        @change="updateData"
        @addPool="addPool"
        @addPrize="addPoolPrize"
      />
    </el-form-item>
    <h3 class="collpase-title">奖池</h3>
    <!-- <el-form-item>
      <el-dropdown>
        <el-button type="primary">
          添加字段<el-icon> <arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click.left="addConfig('单项选择', 'radio')"
              >单项选择</el-dropdown-item
            >
            <el-dropdown-item @click.left="addConfig('多项选择', 'check')"
              >多项选择</el-dropdown-item
            >
            <el-dropdown-item @click.left="addConfig('单行文本', 'input')"
              >单行文本</el-dropdown-item
            >
            <el-dropdown-item @click.left="addConfig('多行文本', 'textarea')"
              >多行文本</el-dropdown-item
            >
            <el-dropdown-item @click.left="addConfig('数值输入', 'number')"
              >数值输入</el-dropdown-item
            >
            <el-dropdown-item @click.left="addConfig('日期', 'date')"
              >日期</el-dropdown-item
            >
            <el-dropdown-item @click.left="addConfig('省市区', 'area')"
              >省市区</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-form-item> -->
  </el-form>
  <addToSignUpMessage
    :show-dialog="showDialog"
    :isEdit="isEdit"
    :data-item="dataItem"
    :fieldConfig="actEntryConfig.fieldConfig"
    @confirm="confirm"
    @edit="editData"
    @cancel="cancel"
  ></addToSignUpMessage>
  <PrizePool
    ref="poolRef"
    v-model="prizeAreas"
    :poolType="[1, 2]"
    :poolBaseInfo="prizePoolType"
    :pageFlag="form.pageFlag"
    :quote="quotePrize"
    @change="updateData"
  ></PrizePool>
</template>
<style lang="scss" scoped>
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }
  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}
.message {
  width: 100%;
  .item {
    display: flex;
    align-items: center;
    .el-icon {
      margin-left: 10px;
      cursor: pointer;
    }
    ._item_operation {
      display: none;
      margin-left: 10px;
    }
    &:hover ._item_operation {
      display: block;
    }
  }
  .el-form-item {
    display: flex;
    margin-bottom: 20px;
  }
  .message-value {
    cursor: pointer;
    line-height: 34px;
    background: #eee;
    width: 300px;
    text-align: center;
    border-radius: 3px;
  }
}
// .el-date-picker {
//   width: 200px;
// }
.to-sign-up-time {
  width: 520px;
}
</style>
